<template>
  <section id="edit-area">
    <section style="border: 1px solid #ccc" id="editor">
      <section id="toolbar-container"></section>
      <section id="editor-title"></section>
      <section id="editor-container" style="height: 495px"></section>
    </section>
    <footer>
      <section>
        <p>标签：</p>
        <a-select
            v-model:value="label"
            mode="multiple"
            style="width:200px"
            placeholder="请选择标签"
            option-label-prop="label"
            :options="labelArr"
            @change="handleChange"
        >
          <template #option="{ value: val, label, icon }">
            <span role="img" :aria-label="val">{{ icon }}</span>
            &nbsp;&nbsp;{{ label }}
          </template>
        </a-select>
      </section>
      <a-button type="primary" class="upload" @click="updataWeeky">保存</a-button>
    </footer>
  </section>
</template>
<script>
import {
  computed,
  defineComponent,
  getCurrentInstance,
  onBeforeUnmount,
  onMounted,
  ref,
  toRefs,
  reactive,
  nextTick
} from 'vue'
import {createEditor, createToolbar, IEditorConfig, IDomEditor, getHtml} from '@wangeditor/editor'
import {PlusOutlined} from '@ant-design/icons-vue';
import $store from "store/index"
import {message} from "ant-design-vue";
import router from "../router";

export default defineComponent({
  name: "editArea",
  components: {
    PlusOutlined,
  },
  setup() {
    const {proxy} = getCurrentInstance()
    let weekyId = ref("")
    let content = ref("")
    let editContent = ref("")
    let ditorTitle = ref("")
    const inputRef = ref();
    let labelArr = ref([])
    let label = ref([])


    const updataWeeky = () => {
            proxy.$request(proxy.$getRoute(43).route_method, proxy.$getRoute(43).route_url, {
              title: ditorTitle.value,
              label: label.value,
              weekly_id: weekyId.value,
              content: content.value,
              edit: editContent.value
            }).then(res => {
              message.success('保存成功', () => {
                history.go(0)
              })
            })
    }

    const handleChange = value => {
      if (label.value.length > 2) {
        label.value = label.value.slice(0, 2)
        message.warn("最多只能选择2个标签")
      }
    };

    onMounted(() => {
      weekyId.value = $store.state.weekyId
      proxy.$request(proxy.$getRoute(26).route_method, proxy.$getRoute(26).route_url.split('{id}')[0] + weekyId.value, {}).then(res => {
        editContent.value = res.data.edit
        content.value = res.data.content
        ditorTitle.value = res.data.title
        label.value = res.data.label.map(x => {
          return x.id
        })
        const editorConfig = {
          MENU_CONF: {}
        }

        const token = $store.state.token
        editorConfig.placeholder = '请输入内容'
        // 当编辑器选区、内容变化时，即触发
        editorConfig.onChange = (editor) => {
          editContent.value = JSON.stringify(editor.children)
          content.value = editor.getHtml()
        }

        editorConfig.MENU_CONF['uploadImage'] = {
          server: 'http://119.23.46.241:11900/api/v1/user/weekly/file',
          fieldName: 'file',
          maxFileSize: 5 * 1024 * 1024, // 单个文件的最大体积限制
          maxNumberOfFiles: 10,// 最多可上传几个文件
          allowedFileTypes: ['image/!*'], // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
          // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
          meta: {
            // Authorization: token
          },
          // 将 meta 拼接到 url 参数中，默认 false
          metaWithUrl: false,
          // 自定义增加 http  header
          headers: {
            Authorization: token
          },
          timeout: 5 * 1000,   // 超时时间，默认为 10 秒
          base64LimitSize: 5 * 1024,    // 小于该值就插入 base64 格式（而不上传），默认为 0
          // 上传之前触发
          onBeforeUpload(files) {
            // files 选中的文件列表，格式如 { key1: file1, key2: file2 }
            return files
            // 返回值可选择：
            // 1. 返回一个对象（files 或者 files 的一部分），则将上传返回结果中的文件
            // 2. 返回 false ，终止上传
          },
          // 上传进度的回调函数
          onProgress(progress) {
            // progress 是 0-100 的数字
            console.log('progress', progress)
          },
          // 单个文件上传成功之后
          onSuccess(file, res) {
            console.log(`${file.name} 上传成功`, res)
          },
          // 单个文件上传失败
          onFailed(file, res) {
            console.log(`${file.name} 上传失败`, res)
          },
          // 上传错误，或者触发 timeout 超时
          onError(file, err, res) {
            console.log(`${file.name} 上传出错`, err, res)
          },
        }

        // 创建编辑器
        const editor = createEditor({
          selector: '#editor-container',
          config: editorConfig,
          content: JSON.parse(res.data.edit),
          mode: 'default'
        })

        const editorTitle = createEditor({
          selector: '#editor-title',
          config: {
            placeholder: "请输入标题",
            maxLength: 50,
            onChange: (editor) => {
              ditorTitle.value = editor.getText()
            }
          },
          content: [
            {
              type: 'header1',
              children: [
                {text: ditorTitle.value}
              ]
            },
          ], // 默认内容，下文有解释
          mode: 'default'
        })
        // 创建工具栏
        const toolbar = createToolbar({
          editor,
          selector: '#toolbar-container',
          mode: 'default'
        })
        // 删除全屏
        toolbar.config.excludeKeys = [
          "|",
          "fullScreen"
        ]
      })

      proxy.$request(proxy.$getRoute(41).route_method, proxy.$getRoute(41).route_url, {}).then(res => {
        labelArr.value = res.data
      })
    })


    return {
      handleChange,
      inputRef,
      updataWeeky,
      labelArr,
      label
    };
  }
})
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="less">
@selectColor: #6777EF;
#edit-area {
  display: flex;
  flex-wrap: wrap;


  #toolbar-container {
    width: 1214px;
  }

  #editor-title {
    border-bottom: solid 1px #cccccc;
  }

  #editor-title p,
  #editor-title h1,
  #editor-title .w-e-text-placeholder {
    font-size: 40px !important;
    font-weight: bold !important;
    font-style: normal !important;
    text-align: center;
  }

  #editor-title p {
    z-index: 10 !important;
  }

  .upload {
    width: 74px;
    height: 36px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: @selectColor;
    color: #fff;
    border: none;
  }

  .upload:hover {
    background: #a3acf5;
  }

  footer {
    margin-top: 30px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  footer > section {
    display: flex;
    align-items: center;
  }

  footer > section > p {
    margin: 0;
  }
}
</style>
